/*
 * @Author: your name
 * @Date: 2021-12-22 12:23:06
 * @LastEditTime: 2021-12-27 12:26:17
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /vue-lazy-load/server/index.js
 */

const express = require('express')
const app = express()
const { resolve } = require('path')
const fs = require('fs')
const { Result } = require('./lib/result')
const { getRandomNumber } = require('./utils/index.js')
/**
 * 公共头部
 */
app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-methods', 'POST,GET')
    next()
})


/**
 * 获取图片列表
 */
app.get('/images', (req, res) => {
    const dataList = JSON.parse(fs.readFileSync('./data/images.json'))
    const imagesList = dataList.map(itm => {
        itm.img = `http://localhost:3000/images/${itm.fileName}`
        return itm
    })
    
    res.send(Result.success(imagesList))
})

/**
 * 获取图片
 */
app.get('/images/:filename', (req, res) => {
    const path = resolve(__dirname, `./images/${req.params.filename}`)
    const time = getRandomNumber(100, 2000)
    console.log('time->:', time)
    setTimeout(() => {
        res.sendFile(path)
    }, time)
})


app.listen(3000, () => {
  console.log('Welcome to use Express 19090!!!!!')
})


const getImgDataList = function (callback) {
    const imgList = fs.readdirSync(resolve(__dirname, './images/'))
    const list = imgList.map((itm, idx) => {
        const newItem = {
            id: idx,
            name: '测试名称_' + idx,
            fileName: itm
        }
        return newItem
    })

    callback(list)
}
